import 'package:flutter/material.dart';

import '../models/playlist.dart';
import '../services/playlist_management_service.dart';
import 'playlist_detail_screen.dart';

class CustomPlaylistsScreen extends StatefulWidget {
  const CustomPlaylistsScreen({super.key});

  @override
  State<CustomPlaylistsScreen> createState() => _CustomPlaylistsScreenState();
}

class _CustomPlaylistsScreenState extends State<CustomPlaylistsScreen> {
  List<Playlist> _playlists = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    final list = await PlaylistManagementService.getPlaylists();
    if (!mounted) return;
    setState(() {
      _playlists = list;
      _loading = false;
    });
  }

  Future<void> _createPlaylist() async {
    final controller = TextEditingController();
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('新增歌单'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: '请输入歌单名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('确定')),
          ],
        );
      },
    );
    if (ok == true) {
      final name = controller.text.trim();
      if (name.isEmpty) return;
      await PlaylistManagementService.createPlaylist(name);
      await _load();
    }
  }

  Future<void> _renamePlaylist(Playlist playlist) async {
    final controller = TextEditingController(text: playlist.name);
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('重命名歌单'),
          content: TextField(
            controller: controller,
            decoration: const InputDecoration(hintText: '新的名称'),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('确定')),
          ],
        );
      },
    );
    if (ok == true) {
      final name = controller.text.trim();
      if (name.isEmpty) return;
      await PlaylistManagementService.renamePlaylist(playlist.id, name);
      await _load();
    }
  }

  Future<void> _deletePlaylist(Playlist playlist) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('删除歌单'),
          content: Text('确定删除“${playlist.name}”吗？此操作不可恢复。'),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, false), child: const Text('取消')),
            FilledButton(onPressed: () => Navigator.pop(context, true), child: const Text('删除')),
          ],
        );
      },
    );
    if (ok == true) {
      await PlaylistManagementService.deletePlaylist(playlist.id);
      await _load();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('管理自定义歌单'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _createPlaylist,
        child: const Icon(Icons.add),
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _playlists.isEmpty
              ? const Center(child: Text('还没有创建任何自定义歌单'))
              : ListView.separated(
                  itemBuilder: (context, index) {
                    final p = _playlists[index];
                    return ListTile(
                      title: Tooltip(
                        message: p.name,
                        waitDuration: const Duration(milliseconds: 300),
                        child: Text(
                          p.name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          softWrap: false,
                        ),
                      ),
                      subtitle: Text('${p.songs.length} 首'),
                      onTap: () async {
                        await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => PlaylistDetailScreen(playlistId: p.id),
                          ),
                        );
                        await _load();
                      },
                      trailing: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          IconButton(
                            icon: const Icon(Icons.edit),
                            tooltip: '重命名',
                            onPressed: () => _renamePlaylist(p),
                          ),
                          IconButton(
                            icon: const Icon(Icons.delete_outline, color: Colors.red),
                            tooltip: '删除',
                            onPressed: () => _deletePlaylist(p),
                          ),
                        ],
                      ),
                    );
                  },
                  separatorBuilder: (_, __) => const Divider(height: 1),
                  itemCount: _playlists.length,
                ),
    );
  }
}